package com.nstar.base.controls
{
	import mx.collections.ArrayCollection;
	import com.nstar.base.util.Logger;
	import mx.utils.ObjectUtil;
	
	public class Pager
	{
		/*
		request.pagenum    当前页 
		request.pagecount	总页数
		request.recordnum	总记录数
		request.pageno		每页显示的记录数
		*/		
		
		private var _pageCount:int;
		private var _source:ArrayCollection ;
		private var _request:Object ;
		private var _recordNum:int;
		private var _pageNo:int;
		private var _pageNum:int;
		
		var logger:Logger = Logger.getInstance();
		
		
		public function get pageCount():int{
			return this._pageCount;
		}
		
		public function get recordNum():int{
			return this._recordNum;
		}
		
		public function get request():Object{
			return _request;
		}
		
		function Pager(source:ArrayCollection,request:Object){
			this._source = source;
			this._request = request;
			
			refresh(request);
			
		}
		
		//更新变量
		private function refresh(request:Object):void{
			_request = request;
			
			if (_request==null){
				throw Error("需要传入分页查询的参数！[ Pager.request = "+_request+" ]");
			}
					
			var n:Number = _source.length/int(_request.pageno);
			_pageCount = n>Math.floor(n)?Math.floor(n)+1:Math.floor(n);
			_recordNum = _source.length;
			
			//如果行数发生变化，则重新从第一页开始显示，防止设置行数过大导致计算当前页上下标索引不正确
			if (int(_request.pageno)!=_pageNo){
				_pageNum = 1;
			}else{
				_pageNum = int(_request.pagenum);
			}
			_pageNo = int(_request.pageno);
			
			_request.pagecount = this._pageCount;
			_request.recordnum = this._recordNum;	

		}
		
		//取得分页数据
		public  function getPagerData(request:Object):ArrayCollection{
			refresh(request);
			
			var result:ArrayCollection = new ArrayCollection();
			
			//求余
			var mod = _source.length % _pageNo;
			//对最后一面的处理，如果上面整除的结果是0,则给mod设置为pageno值
			mod = mod==0?_pageNo:mod;
			
			var start:int = (_pageNum-1) * _pageNo;
			//如果是最后一页，则要重新计算下标索引
			var end:int = (_pageNum==_pageCount?(start+mod):(start + _pageNo)); 
			//取数据
			for(var i:int=start;i<end;i++){
				result.addItem(_source[i]);
			}
			return result;
		}		
	}
}